<template>
  <div class="app-container">
    <!-- 顶部搜索和操作区 -->
    <div class="top-filter-container">
      <div class="search-area">
        <el-select
          v-model="listQuery.product"
          filterable
          remote
          placeholder="请选择商品"
          :remote-method="searchProducts"
          style="width: 220px"
          clearable
        >
          <el-option
            v-for="item in productOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>

        <el-input
          v-model="listQuery.remark"
          placeholder="请输入货架备注"
          style="width: 280px; margin-left: 10px"
          clearable
        />

        <el-checkbox
          v-model="listQuery.showEmpty"
          style="margin-left: 10px"
        >显示零用货架</el-checkbox>

        <el-button
          type="primary"
          icon="el-icon-search"
          style="margin-left: 10px"
          @click="handleFilter"
        >查询</el-button>
      </div>

      <div class="operation-buttons">
        <el-button type="primary" @click="handleCreate">新增</el-button>
        <el-dropdown
          split-button
          type="primary"
          trigger="click"
          @command="handleCommand"
        >
          打印货架标签
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              command="printSelectedLabels"
            >打印选中标签</el-dropdown-item>
            <el-dropdown-item
              command="printAllLabels"
            >打印全部标签</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-button @click="handleBatchDisable">禁用</el-button>
        <el-button @click="handleBatchDelete">删除</el-button>
        <el-button @click="handleImport">导入</el-button>
        <el-button @click="handleExport">导出</el-button>
      </div>
    </div>

    <!-- 主体区域 -->
    <div class="main-content">
      <!-- 左侧仓库树 -->
      <div class="warehouse-tree">
        <el-input
          v-model="warehouseFilter"
          placeholder="请输入仓库名称"
          prefix-icon="el-icon-search"
          clearable
        />

        <el-tree
          :data="warehouseData"
          :props="defaultProps"
          ref="warehouseTree"
          default-expand-all
          node-key="id"
          highlight-current
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          @node-click="handleNodeClick"
        />
      </div>

      <!-- 右侧表格 -->
      <div class="shelf-table">
        <el-table
          ref="multipleTable"
          v-loading="listLoading"
          :data="shelfList"
          tooltip-effect="dark"
          style="width: 100%"
          element-loading-text="加载中"
          border
          @selection-change="handleSelectionChange"
        >
          <!-- <el-table-column type="selection" width="55"></el-table-column> -->

          <el-table-column label="操作" width="100" align="center">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="handleUpdate(scope.row)"
              >
                <i class="el-icon-edit" />
              </el-button>
              <el-button
                type="text"
                size="small"
                @click="handleDelete(scope.row)"
              >
                <i class="el-icon-delete" />
              </el-button>
            </template>
          </el-table-column>

          <el-table-column
            prop="productName"
            label="商品"
            min-width="120"
          />
          <el-table-column
            prop="productCode"
            label="商品编码"
            min-width="120"
            sortable
          />
          <el-table-column
            prop="specification"
            label="规格型号"
            min-width="120"
          />
          <el-table-column
            prop="attribute"
            label="属性"
            min-width="100"
          />
          <el-table-column
            prop="shelfName"
            label="货架名称"
            min-width="120"
            sortable
          >
            <template slot="header">
              货架名称
              <el-tooltip content="点击排序" placement="top">
                <i class="el-icon-sort" />
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="area" label="货区" min-width="100" sortable>
            <template slot="header">
              货区
              <el-tooltip content="点击排序" placement="top">
                <i class="el-icon-sort" />
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column
            prop="warehouse"
            label="仓库"
            min-width="120"
            sortable
          >
            <template slot="header">
              仓库
              <el-tooltip content="点击排序" placement="top">
                <i class="el-icon-sort" />
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column
            prop="availableStock"
            label="仓库可用库存"
            min-width="140"
            sortable
          >
            <template slot-scope="scope">
              <span
                :class="{ 'negative-stock': scope.row.availableStock < 0 }"
              >{{ scope.row.availableStock }}</span>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            background
            :current-page="listQuery.page"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="listQuery.limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 新增/编辑货架对话框 -->
    <el-dialog
      :title="dialogStatus === 'create' ? '新增商品货架' : '编辑商品货架'"
      :visible.sync="dialogFormVisible"
      width="650px"
    >
      <el-form ref="dataForm" :model="temp" :rules="rules" label-width="100px">
        <el-form-item label="商品" prop="productId" class="required-field">
          <el-select
            v-model="temp.productId"
            filterable
            remote
            placeholder="请选择商品"
            style="width: 100%"
            :remote-method="searchProducts"
          >
            <el-option
              v-for="item in productOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="仓库" prop="warehouseId" class="required-field">
          <el-select
            v-model="temp.warehouseId"
            filterable
            placeholder="请选择仓库"
            style="width: 100%"
          >
            <el-option
              v-for="item in warehouseOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="货区" prop="area">
          <el-input v-model="temp.area" placeholder="请输入货区" />
        </el-form-item>

        <el-form-item label="货架名称" prop="shelfName" class="required-field">
          <el-input
            v-model="temp.shelfName"
            placeholder="请输入货架名称"
          />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="temp.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button
          type="primary"
          style="background-color: #42d5d5; border-color: #42d5d5"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'ProductShelves',
  data() {
    return {
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 50,
        product: '',
        remark: '',
        showEmpty: false,
        warehouseId: ''
      },
      productOptions: [],
      warehouseOptions: [],
      warehouseFilter: '',
      warehouseData: [
        {
          id: 'all',
          label: '全部',
          children: [
            { id: 'CK001', label: 'CK001 默认仓库' },
            { id: 'CK002', label: 'CK002 冷藏库' },
            { id: 'CK003', label: 'CK003 食品库' }
          ]
        }
      ],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      shelfList: [],
      multipleSelection: [],
      total: 0,
      dialogFormVisible: false,
      dialogStatus: '',
      temp: {
        id: undefined,
        productId: '',
        warehouseId: '',
        area: '',
        shelfName: '',
        remark: ''
      },
      rules: {
        productId: [
          { required: true, message: '请选择商品', trigger: 'change' }
        ],
        warehouseId: [
          { required: true, message: '请选择仓库', trigger: 'change' }
        ],
        shelfName: [
          { required: true, message: '请输入货架名称', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    warehouseFilter(val) {
      this.$refs.warehouseTree.filter(val)
    }
  },
  created() {
    this.getList()
    this.getProductOptions()
    this.getWarehouseOptions()
  },
  methods: {
    getList() {
      this.listLoading = true
      setTimeout(() => {
        this.shelfList = [
          {
            id: 1,
            productName: '巧克力',
            productCode: 'SP0001',
            specification: '',
            attribute: '',
            shelfName: '三号公司',
            area: '',
            warehouse: '默认仓库',
            availableStock: -74
          },
          {
            id: 2,
            productName: '果味饮料',
            productCode: 'SP0002',
            specification: '',
            attribute: '',
            shelfName: '三号公司',
            area: '',
            warehouse: '默认仓库',
            availableStock: 54
          },
          {
            id: 3,
            productName: '果味饮料',
            productCode: 'SP0002',
            specification: '',
            attribute: '',
            shelfName: '一号公司',
            area: '',
            warehouse: '默认仓库',
            availableStock: 54
          }
        ]
        this.total = this.shelfList.length
        this.listLoading = false
      }, 500)
    },
    getProductOptions() {
      this.productOptions = [
        { id: 1, name: '巧克力' },
        { id: 2, name: '果味饮料' },
        { id: 3, name: '牛奶' },
        { id: 4, name: '面包' }
      ]
    },
    getWarehouseOptions() {
      this.warehouseOptions = [
        { id: 'CK001', name: '默认仓库' },
        { id: 'CK002', name: '冷藏库' },
        { id: 'CK003', name: '食品库' }
      ]
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.toLowerCase().indexOf(value.toLowerCase()) !== -1
    },
    handleNodeClick(data) {
      if (data.id === 'all') {
        this.listQuery.warehouseId = ''
      } else {
        this.listQuery.warehouseId = data.id
      }
      this.getList()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        productId: '',
        warehouseId: '',
        area: '',
        shelfName: '',
        remark: ''
      }
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '创建成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '更新成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确认删除该货架吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          message: '请选择要删除的货架',
          type: 'warning'
        })
        return
      }
      this.$confirm(
        `确认删除所选${this.multipleSelection.length}个货架吗?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.$notify({
            title: '成功',
            message: '批量删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    handleBatchDisable() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          message: '请选择要禁用的货架',
          type: 'warning'
        })
        return
      }
      this.$notify({
        title: '成功',
        message: '批量禁用成功',
        type: 'success',
        duration: 2000
      })
      this.getList()
    },
    searchProducts(query) {
      if (query) {
        // 这里应该是调用API搜索商品，这里只是模拟
        this.productOptions = this.productOptions.filter((item) =>
          item.name.toLowerCase().includes(query.toLowerCase())
        )
      } else {
        this.getProductOptions()
      }
    },
    handleCommand(command) {
      if (command === 'printSelectedLabels') {
        if (this.multipleSelection.length === 0) {
          this.$message({
            message: '请选择要打印标签的货架',
            type: 'warning'
          })
          return
        }
        this.$message({
          message: `打印${this.multipleSelection.length}个标签`,
          type: 'success'
        })
      } else if (command === 'printAllLabels') {
        this.$message({
          message: '打印全部标签',
          type: 'success'
        })
      }
    },
    handleImport() {
      this.$message({
        message: '导入功能',
        type: 'info'
      })
    },
    handleExport() {
      this.$message({
        message: '导出功能',
        type: 'info'
      })
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.top-filter-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-area {
  display: flex;
  align-items: center;
}

.operation-buttons {
  white-space: nowrap;
}

.operation-buttons .el-button {
  margin-left: 10px;
}

.main-content {
  display: flex;
  margin-top: 20px;
  background-color: #fff;
  border: 1px solid #ebeef5;
}

.warehouse-tree {
  width: 220px;
  padding: 10px;
  border-right: 1px solid #ebeef5;
  overflow: auto;
  height: calc(100vh - 240px);
}

.shelf-table {
  flex: 1;
  padding: 10px;
  overflow: auto;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}

.negative-stock {
  color: red;
}

.el-dropdown {
  margin-left: 10px;
  margin-right: 10px;
}

/* 调整树节点的样式 */
.el-tree-node__content {
  height: 32px;
}

.el-tree-node.is-current > .el-tree-node__content {
  background-color: #f0f7ff;
}
</style>
